<template>
  <view class="page">
    <!-- 顶部车辆卡片（展示） -->
    <view class="car-card" v-if="infoReady">
      <image class="car-img" :src="data_info.logo" mode="aspectFill"></image>
      <view class="car-text">
        <view>{{data_info.brand}}、{{curCarName}}</view>
        <view class="sub">{{curCarPrice}}</view>
        <view class="vin">{{base.vin}}</view>
      </view>
    </view>

    <!-- 车辆信息（只展示） -->
    <view class="section">
      <view class="section-title">车辆信息</view>
      <view class="form-card readonly">
        <view class="cell">
          <view class="label">上牌时间</view>
          <view class="value">{{ base.reg_date }}</view>
        </view>
        <view class="cell">
          <view class="label">车牌</view>
          <view class="value">{{ base.plate_no }}</view>
        </view>
        <view class="cell">
          <view class="label">公里数</view>
          <view class="value">{{ base.km }}</view>
        </view>
        <view class="cell">
          <view class="label">内外色</view>
          <view class="value">{{ base.color }}</view>
        </view>
        <view class="cell">
          <view class="label">过户次数</view>
          <view class="value">{{ base.transfer_times }}</view>
        </view>
        <view class="cell">
          <view class="label">是否运营</view>
          <view class="value">{{ base.is_operate }}</view>
        </view>
        <view class="cell">
          <view class="label">所在地</view>
          <view class="value">{{ base.city }}</view>
        </view>
      </view>
    </view>

    <!-- 图片信息（只展示+可预览） -->
    <view class="section">
      <view class="section-title">图片信息</view>
      <view class="form-card readonly">
        <view class="cell" v-for="f in photoFields" :key="f.key">
          <view class="label">{{ f.label }}</view>
          <view class="value">{{ pics[f.key] ? '已上传' : '—' }}</view>
          <image
            v-if="pics[f.key]"
            class="thumb"
            :src="pics[f.key]"
            mode="aspectFill"
            @tap.stop="previewPic(f.key)"
          />
          <text class="ic">👁</text>
        </view>
      </view>
    </view>

    <!-- 预估价格（可编辑） -->
    <view class="section">
      <view class="section-title">预估价格</view>
      <view class="kv-card">
        <picker mode="selector" :range="levelRange" range-key="name" :value="levelIndex" @change="onLevelChange">
          <view class="row" :class="{'err': errors.level}" id="row-level">
            <text class="k">车况等级</text>
            <view class="v v-select">{{ levelRange[levelIndex].name }} <text class="arrow">▾</text></view>
          </view>
        </picker>
        <view class="row" :class="{'err': errors.retail}" id="row-retail">
          <text class="k">零售价</text>
          <view class="v v-edit">
            <input class="num" type="number" v-model="price.retailMin" placeholder="最低价" />
            <text class="dash">-</text>
            <input class="num" type="number" v-model="price.retailMax" placeholder="最高价" />
            <text class="pen">✎</text>
          </view>
        </view>
        <view class="row" :class="{'err': errors.planBuy}" id="row-plan">
          <text class="k">计划收购价格</text>
          <view class="v v-edit">
            <input class="num" type="number" v-model="price.planBuy" placeholder="输入价格" />
            <text class="pen">✎</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 经办记录（测试数据） -->
    <view class="section">
      <view class="section-title">经办记录</view>
      <view class="timeline">
        <view class="t-row t-hd">
          <text class="t-col">节点</text>
          <text class="t-col">经办人/岗位</text>
          <text class="t-col">时间</text>
          <text class="t-col">结果</text>
        </view>
        <view class="t-row" v-for="(item,index) in task_list" :key="index" :style="item.status == 2 ? 'color:#ff0000' : ''">
          <text class="t-col">{{item.step_name}}</text>
          <text class="t-col">{{item.cname}} / {{item.group_name}}</text>
          <text class="t-col">{{item.create_time}}</text>
          <text class="t-col">{{item.status_name}}</text>
        </view>
        <!-- 后续可替换为真实渲染 -->
      </view>
    </view>

    <!-- 意见栏（文本将走单独接口） -->
    <view class="section" v-if="base.my_info && base.my_info.status == 2">
      <view class="section-title">意见栏</view>
      <view class="op-box">
        <textarea v-model="opinion" placeholder="填写审核意见（可选）" maxlength="300" auto-height />
        <view class="hint">当前节点：<text class="danger">{{ task_list[task_list.length-1].step_name }}</text></view>
      </view>
    </view>

    <!-- 底部操作 -->
    <view class="bottom-btn-box" v-if="base.my_info && base.my_info.status == 2">
      <button class="btn btn-gray" @tap="onReject">驳回</button>
      <button class="btn btn-primary" @tap="onApprove">通过</button>
    </view>
  </view>
</template>

<script>
import common_config from '@/static/js/common.js'
var config = common_config.config
var userInfo
var that;
export default {
  data(){
    return{
		task_list:[],
      id:0,
      infoReady:false,
      nodeName:'核训', // 你可以在 onLoad 里通过参数或接口改
      // 展示基表
      base:{
        vin:'', reg_date:'', plate_no:'', km:'', color:'', transfer_times:'', is_operate:'', city:''
      },
      // 价格（可编辑）
      levelRange:[{name:'优（S）',level:'S'},{name:'良（A）',level:'A'},{name:'一般（B）',level:'B'},{name:'差（C）',level:'C'}],
      levelIndex:0,
      price:{ retailMin:'', retailMax:'', planBuy:'' },
      errors:{ level:false, retail:false, planBuy:false },

      // 顶部展示用
      data_info:{carlist:[]}, car_index:-1,
      // 图片（只展示）
      pics:{},
      photoFields:[
        { key:'license', label:'行驶证' },
        { key:'front', label:'车身正前' },
        { key:'front_left', label:'车身左前' },
        { key:'front_right', label:'车身右前' },
        { key:'rear', label:'车身正后' },
        { key:'rear_left', label:'车身左后' },
        { key:'rear_right', label:'车身右后' },
        { key:'dash_meter', label:'仪表台（里程）' },
        { key:'front_seat', label:'前排座椅' },
        { key:'rear_seat', label:'后排座椅' },
        { key:'nameplate', label:'车身铭牌' }
      ],

      // 意见栏
      opinion:''
    }
  },
  computed:{
    curCarName(){ return (this.data_info.carlist && this.data_info.carlist[this.car_index] && this.data_info.carlist[this.car_index].name) || '' },
    curCarPrice(){ return (this.data_info.carlist && this.data_info.carlist[this.car_index] && this.data_info.carlist[this.car_index].price) || '' }
  },
  onLoad(op){
	  that = this;
    this.id = Number(op.id||0)
    this.nodeName = op.node || this.nodeName
    common_config.common_if_login(()=>{}, ()=>{
      userInfo=uni.getStorageSync('userInfo'); try{ userInfo=JSON.parse(userInfo) }catch(e){}
      this.fetchDetail();
	  this.load_task();
    })
  },
  methods:{
    // 详情（用于展示与回填价格）
    fetchDetail(){
      if(!this.id){ common_config.calert('缺少id'); return }
      uni.showLoading({title:'加载中'})
      uni.request({
        url: config.request_url + '/index/pinggu/step1_detail?token=' + (userInfo?.token||''),
        method:'POST', header:{'Content-Type':'application/x-www-form-urlencoded'},
        data:{ id:this.id },
        success: ({data})=>{
          if(Number(data.code)===200 && data.data){
            const d=data.data
            this.base = {
              vin: d.vin || '',
              reg_date: d.reg_date || '',
              plate_no: d.plate_no || '',
              km: d.km || '',
              color: d.color || '',
              transfer_times: d.transfer_times || '',
              is_operate: d.is_operate || '',
              city: d.city || '',
			  status: d.status || '',
			  my_info: d.my_info || '',
            }
            // 价格
            const lv = (Array.isArray(d.levels) && d.levels[0]) ? d.levels[0] : null
            if(lv){
              const idx = this.levelRange.findIndex(x=>x.level === lv.level)
              this.levelIndex = idx>=0 ? idx : 0
              this.price.retailMin = lv.min!==undefined ? String(lv.min) : ''
              this.price.retailMax = lv.max!==undefined ? String(lv.max) : ''
              this.price.planBuy   = lv.plan!==undefined ? String(lv.plan) : ''
            }
            // 图片
            const pm = d.pics || {}
            Object.keys(pm).forEach(k=>{ this.$set(this.pics,k, this.normalizeUrl(pm[k])) })
            // 顶部品牌卡片（可选）
            this.car_index = d.car_index || -1
            this.base.vin && this.fetchTopCard(this.base.vin)
            this.infoReady = true
          }else{
            common_config.calert(data.msg||'加载失败')
          }
        },
        fail:()=>common_config.calert('网络异常'),
        complete:()=>uni.hideLoading()
      })
    },

    // 顶部卡片数据（可选）
    fetchTopCard(vin){
      uni.request({
        url: config.request_url + '/index/pinggu/step1?token=' + (userInfo?.token||''),
        method:'POST', header:{'Content-Type':'application/x-www-form-urlencoded'},
        data:{ vin },
        success: (res)=>{ const r=res.data||{}; if(r.code==200){ this.data_info=r.data||{carlist:[]} } }
      })
    },

    // —— 可编辑价格区 —— //
    onLevelChange(e){ this.levelIndex=Number(e.detail.value); this.errors.level=false },

    validatePrice(){
      const p=this.price
      const errs={
        level: !(this.levelRange[this.levelIndex] && this.levelRange[this.levelIndex].level),
        retail: !(p.retailMin!=='' && p.retailMax!=='' && Number(p.retailMax)>=Number(p.retailMin)),
        planBuy: !(p.planBuy!=='' && Number(p.planBuy)>=0)
      }
      this.errors = Object.assign({}, this.errors, errs)
      if(errs.level){ common_config.calert('请选择车况等级'); return false }
      if(errs.retail){ common_config.calert('请填写完整的零售价区间（最高价 ≥ 最低价）'); return false }
      if(errs.planBuy){ common_config.calert('请输入计划收购价格'); return false }
      return true
    },

    // —— 通过：一次性提交 价格 + 审核意见 —— //
    onApprove(){
      if(!this.validatePrice()) return
    
      // 可选：要求必须写意见再通过
      // if(!this.opinion){ common_config.calert('请填写审核意见'); return }
    
      uni.showModal({
        title:'确认通过',
        content:'将更新该车辆的价格信息，并提交审核意见，是否继续？',
        success: (r)=>{
          if(!r.confirm) return
          const lvl = this.levelRange[this.levelIndex]
          const payload = {
            id: this.id,
            // 价格段：与后端约定统一 key；可扩展多段
            price_levels: JSON.stringify([{
              level: lvl.level,
              name:  lvl.name,
              min:   this.price.retailMin,
              max:   this.price.retailMax,
              plan:  this.price.planBuy
            }]),
            // 审核意见
            opinion: this.opinion || '',
            // 当前节点（可选，便于后端记录）
            node: this.nodeName || ''
          }
    
          uni.request({
            url: config.request_url + '/index/pinggu/agree_step?token=' + (userInfo?.token||''),
            method:'POST',
            header:{'Content-Type':'application/x-www-form-urlencoded'},
            data: payload,
            success: ({data})=>{
              if(Number(data.code)===200){
                uni.navigateTo({
                	url:'/pages/index/sub_success'
                });
              }else{
                common_config.calert(data.msg || '操作失败')
              }
            },
            fail:()=> common_config.calert('网络异常')
          })
        }
      })
    },

    // —— 驳回：不修改信息，二次确认 —— //
    onReject(){
      uni.showModal({
        title:'确认驳回',
        content:'驳回不会修改车辆信息，并删除所有审核节点，回到最初信息登记环节，是否继续？',
        confirmText:'驳回',
        confirmColor:'#ef4444',
        success: (r)=>{
          if(!r.confirm) return;
		  uni.request({
		     url: config.request_url+'/index/pinggu/refuse_step?token='+userInfo.token,
		  	data:{bak:that.opinion || '',cid:that.id},
		      header: {
		           "Content-Type": "application/x-www-form-urlencoded",
		      },
		  	method:'POST',
		      success: (res) => {
		  		res = res.data;
		        if(res.code == 200){
		        	uni.navigateTo({
		        		url:'/pages/index/sub_success?act=refuse'
		        	});
		        }else{
		        	common_config.calert(res.msg);
		        }
		      }
		  });
         
        }
      })
    },
	//经办记录
	load_task(){
		uni.request({
		  url: config.request_url+'/index/pinggu/load_task_list?token='+userInfo.token+'&cid='+that.id,
		  method: 'GET',
		  success: (res) => {
			  console.log(res);
			res = res.data;
			
			if(res.code == 200){
				this.task_list = res.data;
				//common_config.calert('测试');
			}else{
				common_config.calert(res.msg);
			}
		  },
		  complete: () => {
		   
		  }
		})
	},
    // 仅更新价格的接口（后端建议提供 /index/pinggu/update_price）
    updatePrice(){
      return new Promise((resolve,reject)=>{
        const lvl = this.levelRange[this.levelIndex]
        const payload = {
          id: this.id,
          price_levels: JSON.stringify([{
            level:lvl.level, name:lvl.name,
            min:this.price.retailMin, max:this.price.retailMax, plan:this.price.planBuy
          }])
        }
        uni.request({
          url: config.request_url + '/index/pinggu/update_price?token=' + (userInfo?.token||''),
          method:'POST', header:{'Content-Type':'application/x-www-form-urlencoded'},
          data: payload,
          success: ({data})=>{
            if(Number(data.code)===200) resolve()
            else reject(data.msg||'更新价格失败')
          },
          fail:()=>reject('网络异常')
        })
      })
    },

    // 意见单独入库（预留，你后端可实现 /index/pinggu/opinion_add）
    submitOpinion(action){
      return new Promise((resolve,reject)=>{
        // 若不想提交意见，可直接 resolve()
        uni.request({
          url: config.request_url + '/index/pinggu/opinion_add?token=' + (userInfo?.token||''),
          method:'POST', header:{'Content-Type':'application/x-www-form-urlencoded'},
          data: {
            ref_id: this.id,
            node: this.nodeName,
            action, // pass/reject
            content: this.opinion || ''
          },
          success: ({data})=>{
            if(Number(data.code)===200) resolve()
            else resolve() // 不阻断主流程
          },
          fail:()=>resolve()
        })
      })
    },

    // 工具
    normalizeUrl(u){
      if(!u) return ''
      u = String(u).trim()
      if(/^https?:\/\//i.test(u)) return u
      if(/^\/\//.test(u)) return 'https:' + u
      const base = (config.cdn || config.request_url || '').replace(/\/+$/,'')
      if(!base) return u
      if(u[0] !== '/') u = '/' + u
      return base + u
    },

    previewPic(key){
      const url = this.pics[key]
      if(!url) return
      // 预览所有图，当前置顶
      const urls = this.photoFields.map(f=>this.pics[f.key]).filter(Boolean)
      const idx = urls.indexOf(url)
      uni.previewImage({ urls, current: idx>=0?idx:0 })
    }
  }
}
</script>

<style>
.page{background:#f6f8ff;min-height:100vh;padding:32rpx 32rpx 140rpx;}

/* 顶部卡片 */
.car-card{background:#fff;border-radius:20rpx;padding:20rpx;display:flex;gap:20rpx;align-items:center;margin-bottom:28rpx;box-shadow:0 4rpx 12rpx rgba(0,0,0,0.05);}
.car-img{width:220rpx;height:130rpx;border-radius:12rpx;flex-shrink:0;}
.car-text{flex:1;font-size:28rpx;color:#333;line-height:1.6;}
.car-text .sub{color:#777;font-size:26rpx;}
.vin{font-size:26rpx;color:#888;margin-top:4rpx;}

.section{background:#fff;border-radius:20rpx;padding:24rpx;margin-bottom:28rpx;box-shadow:0 4rpx 12rpx rgba(0,0,0,0.04);}
.section-title{font-size:30rpx;font-weight:600;color:#333;margin-bottom:12rpx;}

.form-card{background:#fff;border:1rpx solid #e8eef6;border-radius:16rpx;overflow:hidden;}
.form-card.readonly .cell{opacity:.95}
.cell{display:flex;align-items:center;padding:22rpx 18rpx;border-bottom:1rpx solid #edf2f7;}
.cell:last-child{border-bottom:none;}
.label{width:240rpx;font-size:28rpx;color:#475569;}
.value{flex:1;font-size:28rpx;color:#111827;}
.ic{width:44rpx;text-align:right;font-size:28rpx;color:#9aa5b1;margin-left:10rpx;}
.thumb{width:72rpx;height:72rpx;border-radius:8rpx;margin-right:12rpx;}

/* 预估价格卡片（可编辑） */
.kv-card{border:1rpx solid #e8eef6;border-radius:16rpx;overflow:hidden;}
.row{display:flex;align-items:center;justify-content:space-between;padding:22rpx 18rpx;border-bottom:1rpx solid #edf2f7;}
.row:last-child{border-bottom:none;}
.k{font-size:28rpx;color:#475569;}
.v{display:flex;align-items:center;font-size:28rpx;color:#111827;}
.v-select{color:#111827;}
.arrow{margin-left:8rpx;font-size:24rpx;color:#8b98a5;}
.v-edit{gap:10rpx;}
.num{width:160rpx;border:none;background:transparent;font-size:28rpx;text-align:right;color:#111827;}
.dash{margin:0 6rpx;color:#8b98a5;}
.pen{margin-left:8rpx;color:#8b98a5;font-size:26rpx;}
.row.err{background:#fff7f7;border-left:8rpx solid #ef4444;}

/* 经办记录 */
.timeline{border:1rpx solid #e8eef6;border-radius:16rpx;overflow:hidden;}
.t-row{display:flex;padding:20rpx 16rpx;border-bottom:1rpx solid #edf2f7;font-size:26rpx;color:#374151;}
.t-row:last-child{border-bottom:none;}
.t-hd{background:#f9fbff;font-weight:600;color:#111827;}
.t-col{flex:1;}

/* 意见栏 */
.op-box{border:1rpx solid #e8eef6;border-radius:16rpx;padding:16rpx;}
.op-box textarea{width:100%;font-size:28rpx;color:#111827;min-height:120rpx;}
.hint{margin-top:10rpx;color:#6b7280;font-size:24rpx;}
.danger{color:#ef4444}

/* 底部按钮 */
.bottom-btn-box{position:fixed;left:0;right:0;bottom:0;background:#fff;padding:18rpx 28rpx;display:flex;gap:20rpx;box-shadow:0 -4rpx 10rpx rgba(0,0,0,0.06);}
.btn{flex:1;height:90rpx;line-height:90rpx;border-radius:45rpx;font-size:30rpx;font-weight:600;text-align:center;}
.btn-gray{background:#f1f5f9;color:#111827;}
.btn-primary{background:#007aff;color:#fff;}
.btn:active{opacity:.92;}
</style>
